package com.tca.common.data.mybatis.handler;

import com.tca.common.core.bean.DataScope;
import com.tca.common.core.datapermission.DataPermissionContextHolder;
import com.tca.common.core.utils.ValidateUtils;
import com.tca.common.data.mybatis.config.DataPermissionProperties;
import com.tca.common.data.mybatis.utils.CamelCaseUtils;
import org.apache.ibatis.reflection.MetaObject;

import java.time.LocalDateTime;

/**
 * @author zhoua
 * @Date 2021/7/10
 */
public class MetaObjectHandler implements com.baomidou.mybatisplus.core.handlers.MetaObjectHandler {
    
    private DataPermissionContextHolder dataPermissionContextHolder;
    
    private DataPermissionProperties dataPermissionProperties;
    
    public MetaObjectHandler(DataPermissionContextHolder dataPermissionContextHolder,
                             DataPermissionProperties dataPermissionProperties) {
        this.dataPermissionContextHolder = dataPermissionContextHolder;
        this.dataPermissionProperties = dataPermissionProperties;
    }

    /**
     * 填充创建时间
     * @param metaObject
     */
    @Override
    public void insertFill(MetaObject metaObject) {
        // 自动填充时间
		this.strictInsertFill(metaObject, "createTime", LocalDateTime.class, LocalDateTime.now());
        this.strictInsertFill(metaObject, "updateTime", LocalDateTime.class, LocalDateTime.now());
    
        if (!dataPermissionProperties.isEnabled()) {
            return;
        }
        DataScope dataScope = dataPermissionContextHolder.getDataScope();
        if (ValidateUtils.isEmpty(dataScope)) {
            return;
        }
    
        // 有租户字段且为空, 自动填充
        String tenantFieldName = CamelCaseUtils.toCamelCaseField(dataPermissionProperties.getTenantColumn());
        if (metaObject.hasSetter(tenantFieldName) && ValidateUtils.isNotEmpty(dataScope.getTenant())
            && ValidateUtils.isEmpty(metaObject.getValue(tenantFieldName))) {
            this.strictInsertFill(metaObject, tenantFieldName, Long.class, Long.parseLong(dataScope.getTenant()));
        }
        // 有部门字段且为空, 自动填充
        String departmentFieldName = CamelCaseUtils.toCamelCaseField(dataPermissionProperties.getDepartmentColumn());
        if (metaObject.hasSetter(departmentFieldName) && ValidateUtils.isNotEmpty(dataScope.getDepartment())
                && ValidateUtils.isEmpty(metaObject.getValue(departmentFieldName))) {
            this.strictInsertFill(metaObject, departmentFieldName, Long.class, Long.parseLong(dataScope.getDepartment()));
        }
        
    
    }

    /**
     * 填充更新时间
     * @param metaObject
     */
    @Override
    public void updateFill(MetaObject metaObject) {
        this.strictUpdateFill(metaObject, "updateTime",  LocalDateTime.class, LocalDateTime.now());
    }
    
    
}
